package com.wh.testCAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

//CAS compareAndSet 比较并交换  带时间戳的原子引用
public class CASDemo2 {
    public static void main(String[] args) {
        //两个参数 1：初始化的值  2:时间戳
        AtomicStampedReference<Integer> reference = new AtomicStampedReference<>(60,1);

        new Thread(()->{
            //获得版本号
            int stamp = reference.getStamp();
            System.out.println("a1-->"+stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = reference.compareAndSet(60, 61, reference.getStamp(), reference.getStamp() + 1);
            System.out.println("a2-->"+b);
            System.out.println("a2-->"+reference.getStamp());

            boolean b1 = reference.compareAndSet(61, 60, reference.getStamp(), reference.getStamp() + 1);
            System.out.println("a3-->"+b1);
            System.out.println("a3-->"+reference.getStamp());
        },"A").start();
        new Thread(()->{
            int stamp = reference.getStamp();
            System.out.println("b1-->"+stamp);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = reference.compareAndSet(60, 88, stamp, stamp+ 1);
            System.out.println("b2-->"+b);
        },"B").start();
    }
}
